﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GmPrizedrawTool
{
    public class CsvHelper
    {
        /// <summary>
        /// 读取CSV文件
        /// </summary>
        /// <param name="fullFileName">文件全名</param>
        /// <param name="firstRow">开始行</param>
        /// <param name="firstColumn">开始列</param>
        /// <param name="getRows">获取多少行</param>
        /// <param name="getColumns">获取多少列</param>
        /// <param name="haveTitleRow">是有标题行</param>
        /// <returns>DataTable</returns>
        public static DataTable OpenCSV(string fullFileName, int firstRow = 0, int firstColumn = 0, int getRows = 0, int getColumns = 0, bool haveTitleRow = false)
        {
            try
            {
                DataTable dt = new DataTable();
                FileStream fs = new FileStream(fullFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                Encoding gbk = Encoding.GetEncoding("GBK");
                StreamReader sr = new StreamReader(fs, gbk);
                //记录每次读取的一行记录
                string strLine = string.Empty;
                //记录每行记录中的各字段内容
                string[] aryLine;
                //标示列数
                int columnCount = 0;
                //是否已建立了表的字段
                bool bCreateTableColumns = false;
                //第几行
                int iRow = 0;

                //去除无用行
                if (firstRow > 0)
                {
                    for (int i = 1; i < firstRow; i++)
                    {
                        sr.ReadLine();
                    }
                }

                string[] separators = { "," };
                string AllString = sr.ReadToEnd();
                string[] RowStringArr = AllString.Split("\r\n");
                //逐行读取CSV中的数据
                //while ((strLine = sr.ReadLine()) != null)
                while (iRow <= RowStringArr.Length - 1)
                {
                    if (string.IsNullOrEmpty(RowStringArr[iRow]))
                    {
                        iRow = iRow + 1;
                        continue;
                    }
                    DataRow dr = dt.NewRow();
                    aryLine = RowStringArr[iRow].Split(','); //strLine.Split(',');//分割后的数组
                    //构建表头
                    if (bCreateTableColumns == false)
                    {
                        bCreateTableColumns = true;
                        columnCount = aryLine.Length;
                        //创建列
                        for (int i = firstColumn; i < (getColumns == 0 ? columnCount : firstColumn + getColumns); i++)
                        {
                            DataColumn dc
                                = new DataColumn(haveTitleRow == true ? aryLine[i] : "COL" + i.ToString());
                            dt.Columns.Add(dc);
                        }

                        bCreateTableColumns = true;

                        if (haveTitleRow == true)
                        {
                            continue;
                        }
                    }
                    //构建后续行
                    List<string> newAryLine = new List<string>();
                    for (int i = 0; i < aryLine.Length; i++)
                    {
                        if (aryLine[i].Contains('"') && CheckTargetCharCount(aryLine[i], '"') == 1)
                        {
                            string colVal = aryLine[i];
                            for (int j = (i + 1); j < aryLine.Length; j++)
                            {
                                if (aryLine[j].Contains('"'))
                                {
                                    colVal += "," + aryLine[j];
                                    i = j;
                                    break;
                                }
                                else
                                {
                                    colVal += "," + aryLine[j];
                                }
                            }
                            //newAryLine.Add(colVal.Replace("\"",""));
                            newAryLine.Add(colVal);
                        }
                        else
                        {
                            newAryLine.Add(aryLine[i]);
                        }
                    }

                    for (int j = firstColumn; j < newAryLine.Count; j++)
                    {
                        if (j < dt.Columns.Count)
                        {
                            dr[j - firstColumn] = newAryLine[j];
                        }

                    }
                    dt.Rows.Add(dr);

                    iRow = iRow + 1;
                    if (getRows > 0)
                    {
                        if (iRow > getRows)
                        {
                            break;
                        }
                    }

                }

                sr.Close();
                fs.Close();
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 将DataTable写入到新的csv文件
        /// </summary>
        /// <param name="table">表数据</param>
        /// <param name="filePath">csv文件地址</param>
        /// <param name="IsHaveHeader">表数据是否包含表头</param>
        public static void WriteDataTableToCsv(DataTable table, string filePath, bool IsHaveHeader)
        {
            StringBuilder csv = new StringBuilder();

            // 添加列标题
            if (!IsHaveHeader)
            {
                foreach (DataColumn column in table.Columns)
                {
                    csv.Append(column.ColumnName + ",");
                }
                csv.Append("\r\n");
            }
            // 添加行数据  
            foreach (DataRow row in table.Rows)
            {
                foreach (var item in row.ItemArray)
                {
                    csv.Append(item.ToString() + ","); // 处理逗号  
                }
                csv.Length--; // 去掉最后一个多余的逗号  
                csv.Append("\r\n");
            }
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Encoding gbk = Encoding.GetEncoding("GBK");
            // 写入文件  
            File.WriteAllText(filePath, csv.ToString(), gbk);
        }

        /// <summary>
        /// 判断指定字符在字符串中出现的次数
        /// </summary>
        /// <param name="targetStr"></param>
        /// <param name="targetChar"></param>
        /// <returns></returns>
        public static int CheckTargetCharCount(string targetStr, char targetChar)
        {
            if (targetStr.Length > 0)
            {
                int count = 0;
                foreach (char c in targetStr)
                {
                    if (c == targetChar)
                    {
                        count++;
                    }
                }
                return count;
            }
            return 0;
        }
    }
}
